package com.example.moban.base;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.example.moban.R;
//import com.hyphenate.EMCallBack;
//import com.hyphenate.EMConnectionListener;
//import com.hyphenate.EMError;
//import com.hyphenate.chat.EMClient;
//import com.hyphenate.util.NetUtils;

import com.example.moban.utils.Lerist;
import com.example.moban.utils.SharedPreferenceUtils;
import com.example.moban.view.dialog.IvTvDialog;
import com.example.moban.view.dialog.SimpleDialogFragment;
import com.example.moban.view.dialog.SuccessLoginDialog;
import com.rzhd.coursepatriarch.common.handle.FixMemLeak;
import com.rzhd.coursepatriarch.common.utils.NetworkMyUtil;
import com.rzhd.coursepatriarch.common.utils.ScreenSizeUtils;
import com.rzhd.coursepatriarch.common.utils.StatusBarUtils;
import com.rzhd.coursepatriarch.common.utils.ToastUtils;
import com.rzhd.coursepatriarch.common.utils.rxbus.RxBus;
import com.rzhd.coursepatriarch.common.utils.rxbus.RxBusBaseMessage;
import com.rzhd.coursepatriarch.common.view.CustomToolbar;


import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.List;

import butterknife.ButterKnife;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;


/**
 * @author yql
 * @date 2017/11/8
 */

public abstract class BaseActivity extends SwipeBackActivity implements View.OnClickListener /* , EMConnectionListener*/{

    protected Activity mContext;
    private View mContentView;
    protected RelativeLayout allParentView;
    protected RelativeLayout mContentLayoutView;
    private LinearLayout brokenNetwork;
    protected View mStatusBarHeight;
    protected ImageView returnImage;
    protected CustomToolbar mCustomToolbar;
//    protected String TAG = this.getClass().getSimpleName() + "日志";
    protected boolean openNetworkView = false;

    /**
     * 是否显示下线弹框
     */
    private boolean showOfflineDialog = true;

    /**
     * 屏幕默认方向
     */
    protected int screenDefaultDirection = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
    private Handler handler = new Handler();
    protected Resources resources;
    protected SharedPreferenceUtils preferenceUtils;
    protected static final int LOAD_WAY_REFRESH = 1;
    protected static final int LOAD_WAY_LOADMORE = 2;

    private boolean mIsSoftKeyboardShowing;
    private boolean isPopBottomLayout;
    protected int endHeight;
    private boolean isOpenKeyboarded;
    private float topViewEndHeight;
    protected SwipeBackLayout swipeBackLayout;
    protected boolean isAddConnectListener = true;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
//        Log.e(TAG, "the_life_cycle——onCreate");
        mContext = this;
        super.onCreate(savedInstanceState);
        super.setContentView(com.rzhd.coursepatriarch.common.R.layout.activity_base);

        //设置状态栏颜色(比较low的实现沉浸式功能),设置颜色与toolbar颜色相同就行了
        allParentView = (RelativeLayout) findViewById(com.rzhd.coursepatriarch.common.R.id.allParentView);
        mContentLayoutView = (RelativeLayout) findViewById(com.rzhd.coursepatriarch.common.R.id.mContentLayoutView);
        mStatusBarHeight = findViewById(com.rzhd.coursepatriarch.common.R.id.statusBarHeight);
        mCustomToolbar = (CustomToolbar) findViewById(com.rzhd.coursepatriarch.common.R.id.customToolbar);
        brokenNetwork = (LinearLayout) findViewById(com.rzhd.coursepatriarch.common.R.id.brokenNetwork);
        returnImage = (ImageView) findViewById(com.rzhd.coursepatriarch.common.R.id.returnBtn);
        //初始化toolbar
        initToolbar();
        resources = getResources();
        preferenceUtils = SharedPreferenceUtils.getInstance(  this );
        brokenNetwork.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickBrokenNetwork();
            }
        });
        setContentView(savedInstanceState);
        initDrawer();


        //设置状态栏字体颜色  国产机适配
//        StatusBarUtils.StatusBarLightMode(this, true);
//        //状态栏高度5.0以上的才设置状态栏高度
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            int height = StatusBarUtils.getStatusBarHeight(mContext);
//            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mStatusBarHeight.getLayoutParams();
//            layoutParams.height = height;
//            mStatusBarHeight.setBackgroundColor( getResources().getColor( R.color.black ));
//            mStatusBarHeight.setLayoutParams(layoutParams);
//        }
        swipeBackLayout = getSwipeBackLayout();
        swipeBackLayout.setEdgeTrackingEnabled( SwipeBackLayout.STATE_IDLE );
        initView();
        if (!NetworkMyUtil.getInstance(mContext).isHaveNetWork() && openNetworkView) {
            changeContentView(false);
        } else {
            initData();
        }
        //界面竖屏显示(默认竖屏)
        setRequestedOrientation(screenDefaultDirection);
    }

    protected void initDrawer(){

    }

    /**
     * 初始化toolbar
     */
    private void initToolbar() {
//        mCustomToolbar.setBackgroundResource( R.mipmap.tab );
        //设置背景颜色
        mCustomToolbar.setBackgroundColor(getResources().getColor(R.color.white));
        //设置字体颜色
        mCustomToolbar.setToolbarDefaultColor(getResources().getColor(R.color.color_303030 ) );
        //设置右侧颜色
        mCustomToolbar.getToolbarRightText().setTextColor(getResources().getColor(R.color.color_303030));
        //设置返回图标
        returnImage.setImageResource(R.mipmap.icon_black_back);
        returnImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    public void setContentView(int layoutResID) {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mContentView = inflater.inflate(layoutResID, mContentLayoutView, false);
        mContentLayoutView.addView(mContentView, 0);
        ButterKnife.bind(this);
        addSubscription(RxBusBaseMessage.EventCode.TO_LOGIN_PAGE_TOKEN, new Consumer<RxBusBaseMessage>() {
            @Override
            public void accept(RxBusBaseMessage rxBusBaseMessage) throws Exception {
                Log.i( "TAG" , "======================显示toke=============" );
                //没有显示弹框展示  并设置为true  下次就不展示弹框
//                if (!BaseApplication.getInstance().showMultiLevelLoginDialog && showOfflineDialog) {
//                    BaseApplication.getInstance().showMultiLevelLoginDialog = true;
////                    new LoginOutUtils(getApplicationContext()).switchUser();
//                    showActivity(MultiLevelLoginDialogActivity.class);
//                }
            }
        });
    }


    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        if( isAddConnectListener ){
//            EMClient.getInstance().addConnectionListener( this );//环信
//        }
    }


    @Override
    protected void onDestroy() {
//        Log.e(TAG, "the_life_cycle——onDestroy");
        super.onDestroy();
        RxBus.getInstance().unSubscribe(this);
        //====================2019-1-28新增==================
        //解决华为输入框内存泄漏的问题
        FixMemLeak.fixLeak( this );
        //====================2019-1-28新增==================
    }

    /**
     * 设置布局
     */
    public abstract void setContentView(Bundle savedInstanceState);


    /**
     * 初始化View
     */
    public abstract void initView();

    /**
     * 初始化数据
     */
    public abstract void initData();

    private void changeContentView(boolean haveNetwork) {
        mContentLayoutView.setVisibility(haveNetwork ? View.VISIBLE : View.GONE);
        brokenNetwork.setVisibility(haveNetwork ? View.GONE : View.VISIBLE);
    }

    /**
     * 点击断网图片
     */
    protected void clickBrokenNetwork() {
        boolean haveNetwork = NetworkMyUtil.getInstance(mContext).isHaveNetWork();
        if (!haveNetwork) {
            ToastUtils.shortToast("请检查网络连接");
            return;
        }
        changeContentView(haveNetwork);
    }

    /**
     * 订阅消息
     *
     * @param code     消息类型
     * @param consumer
     */
    protected void addSubscription(@RxBusBaseMessage.EventCode int code, Consumer<RxBusBaseMessage> consumer) {
        Disposable disposable = RxBus.getInstance().toObservable(code, RxBusBaseMessage.class, consumer, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                Log.e("Tag", "addSubscription  error" + throwable.toString());
            }
        });
        //保存订阅对象  方便取消订阅
        RxBus.getInstance().addSubscription(this, disposable);
    }

    /*--------------------------------------界面跳转--------------------------------------*/

    /***
     * @param intent
     */
    public void showActivity(Intent intent) {
        super.startActivity(intent);
    }

    /**
     * @param cls 目标界面
     */
    public void showActivity(Class<?> cls) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        super.startActivity(intent);
    }

    /**
     * @param cls    目标界面
     * @param extras 传值数据
     */
    public void showActivity(Class<?> cls, Bundle extras) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        intent.putExtras(extras);
        super.startActivity(intent);
    }

    /**
     * @param cls         目标界面
     * @param requestCode 请求码
     */
    public void showActivity(Class<?> cls, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        super.startActivityForResult(intent, requestCode);
    }

    /**
     * @param cls         目标界面
     * @param extras      传值数据
     * @param requestCode 请求码
     */
    public void showActivity(Class<?> cls, Bundle extras, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        intent.putExtras(extras);
        super.startActivityForResult(intent, requestCode);
    }

    /**
     * 获取上个界面的信息
     *
     * @param key 布尔值
     * @return
     */
    public Boolean getBundleValueBoolean(String key, boolean defaultValue) {
        Boolean value;
        if (key.equals("") || key == null || getIntent().getExtras() == null) {
            return defaultValue;
        }
        Bundle bundle = getIntent().getExtras();
        value = bundle.getBoolean(key, defaultValue);
        return value;
    }

    /**
     *
     * @param key 字符串
     * @return
     */
    public Object getBundleValueSerializable(String key) {
        if (key.equals("") || key == null || getIntent().getExtras() == null) {
            return null;
        }
        Bundle bundle = getIntent().getExtras();
        return bundle.getSerializable( key );
    }

    /**
     * 获取上个界面的信息
     *
     * @param key 字符串
     * @return
     */
    public String getBundleValueString(String key) {
        String value;
        if (key.equals("") || key == null || getIntent().getExtras() == null) {
            return "";
        }
        Bundle bundle = getIntent().getExtras();
        value = bundle.getString(key, "");
        return value;
    }

    /**
     * 获取上个界面的信息
     *
     * @param key int
     * @return
     */
    public int getBundleValueInt(String key, int defaultValue) {
        int value;
        Intent intent = getIntent();
        Bundle bundle1 = intent.getExtras();
        if (key.equals("") || key == null || getIntent().getExtras() == null) {
            return defaultValue;
        }
        Bundle bundle = getIntent().getExtras();
        value = bundle.getInt(key, defaultValue);
        return value;
    }

    public void setShowOfflineDialog(boolean showOfflineDialog) {
        this.showOfflineDialog = showOfflineDialog;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            //TODO something
            onKeyDown();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    protected void onKeyDown(){
        finish();
    }

    /*--------------------------------界面数据处理----------------------------------*/

    /**
     * 是否登录
     *
     * @return
     */
    protected boolean isLogin() {
        return SharedPreferenceUtils.getInstance(mContext).getLogin();
    }

    /**
     * 获取用户id
     *
     * @return
     */
    protected String getUserId() {
//        return SharedPreferenceUtils.getInstance(mContext).getUserId();
        return "";
    }

    /**
     * 获取token
     *
     * @return
     */
//    public String getToken() {
//        return SharedPreferenceUtils.getInstance(mContext).getToken();
//    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void handleLoginEvent(LoginEvent event) {
//        if (event != null
//                && !TextUtils.isEmpty(event.getOpeName())
//                && event.getOpeName().equals(LoginEvent.Constants.TO_LOGIN_PAGE_TOKEN)) {
//            new LoginOutUtils((AppCompatActivity) mContext).switchUser();
//        }
//    }

    /**
     * 请求全屏
     */
    protected void requestFulScreen(){
        requestFulScreen( false , true , false );
    }

    protected void requestFulScreen( boolean isFitsSystemWindows , boolean isFullScreen , boolean isTextDark ){
        //首页开始全屏模式
        allParentView.setFitsSystemWindows( isFitsSystemWindows );
        StatusBarUtils.StatusBarLightMode(mContext, isFullScreen );
        //状态栏为为透明
        mStatusBarHeight.setVisibility(View.GONE);
        StatusBarUtils.setColor(mContext, Color.TRANSPARENT, 0, isTextDark );
    }

    /**
     * 显示提示弹窗
     * @param hit
     * @param isSuccess
     * @param listener
     */
    protected void showCenterHitDialog(String hit , final boolean isSuccess ,
                                       SuccessLoginDialog.OnDialogCancelListener listener ){
        SuccessLoginDialog dialog = new SuccessLoginDialog();
        dialog.setDialogCancelListener( listener );
        dialog.showDialog(getSupportFragmentManager(),hit ,
                getResources().getDrawable(R.drawable.shape_242222_radius13), 0);
    }

    /**
     * 显示自动关闭弹窗
     * @param hit
     * @param isCancelAble
     * @param listener
     */
    protected void showAutoAlertDialog( String hit , boolean isCancelAble ,
                                        SimpleDialogFragment.DialogTimeOverBack listener ){
        IvTvDialog dialog = new IvTvDialog();
        dialog.setCancelable( isCancelAble );
        dialog.setDialogTimeOverBack( listener );
        dialog.showDialog( getSupportFragmentManager() , hit );
    }

    /**
     * 旋转view
     * @param view
     */
    protected void rotateViewRepeat( View view ){
        Animation roteAnimation = new RotateAnimation(0.0f, 360f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        roteAnimation.setRepeatCount(-1);
        roteAnimation.setInterpolator(new LinearInterpolator());
        roteAnimation.setDuration(2000);
        view.startAnimation(roteAnimation);
    }

    protected void rotateView(final View view , float angle , AnimatorListenerAdapter adapter ){
        view.animate()
            .setDuration( 700 )
            .setInterpolator( new AccelerateDecelerateInterpolator())
            .rotation( angle )
            .setListener(adapter).start();
    }

    //===========================用于解决ScrollView与EditText滚动冲突问题=========================
    /**
     * EditText竖直方向是否可以滚动
     * @param editText  需要判断的EditText
     * @return  true：可以滚动   false：不可以滚动
     */
    protected boolean canVerticalScroll(EditText editText) {
        //滚动的距离
        int scrollY = editText.getScrollY();
        //控件内容的总高度
        int scrollRange = editText.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() -editText.getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;

        if(scrollDifference == 0) {
            return false;
        }

        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }
    //===========================用于解决ScrollView与EditText滚动冲突问题=========================
    /**
     * 关闭刷新
     * @param loadWay
     */
    protected void closeRefresh( int loadWay , SmartRefreshLayout refreshLayout ){
        if( refreshLayout == null ){
            return;
        }
        if( loadWay == LOAD_WAY_REFRESH ){
            refreshLayout.finishRefresh();
        }else{
            refreshLayout.finishLoadMore();
        }
    }

    /**
     * 显示或隐藏空试图
     * @param emptyView
     * @param datas
     */
    protected void showOrHideListEmptyView( View emptyView , List datas ){
        if( emptyView == null ){
            return;
        }
        if( datas != null && datas.size() <= 0 ){
            emptyView.setVisibility( View.VISIBLE );
        }else{
            emptyView.setVisibility( View.GONE );
        }
    }

    /**
     * 软键盘监听器
     */
    protected ViewTreeObserver.OnGlobalLayoutListener mOnGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            onGlobalLayoutMethodTwo();
        }
    };

    private void onGlobalLayoutMethodTwo() {
        int screenHeight = ScreenSizeUtils.getInstance( this ).getScreenHeight();
        //判断窗口可见区域大小
        Rect r = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
        //如果屏幕高度和Window可见区域高度差值大于整个屏幕高度的1/3，则表示软键盘显示中，否则软键盘为隐藏状态。
        int heightDifference = screenHeight - (r.bottom - r.top);
        boolean isKeyboardShowing = heightDifference > screenHeight / 3;

        //如果之前软键盘状态为显示，现在为关闭，或者之前为关闭，现在为显示，则表示软键盘的状态发生了改变
        if ((mIsSoftKeyboardShowing && !isKeyboardShowing) || (!mIsSoftKeyboardShowing && isKeyboardShowing)) {
            mIsSoftKeyboardShowing = isKeyboardShowing;
        }
        changeViewPlace(mIsSoftKeyboardShowing, r);
    }

    /**
     * 改变view的位置
     *
     * @param mIsSoftKeyboardShowing 是否显示软键盘
     * @param rect                   屏幕可视区矩形对象，通过该对象可以获取可视区的相关坐标和高度
     */
    protected void changeViewPlace(boolean mIsSoftKeyboardShowing, Rect rect) {
    }

    /**
     * 刷新发布信息的布局视图
     *
     * @param bottomMaskingView
     * @param rect
     */
    protected void refreshPublishLayout(final View bottomMaskingView, Rect rect, KeybordListener listener) {
        if (mIsSoftKeyboardShowing) {
            if (!isPopBottomLayout) {
                endHeight = ScreenSizeUtils.getInstance( mContext ).getScreenHeight() - rect.bottom;
                bottomMaskingView.setMinimumHeight( rect.bottom );
                //当设备系统版本高于5.0时才显示底部视图，否则会出现输入框被顶到界面最上边
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    bottomMaskingView.setVisibility(View.VISIBLE);
                }
                showPublishViewAnim(bottomMaskingView,0, endHeight,
                        new MyAnimListener() {
                            @Override
                            public void onAnimationEnd() {
                                bottomMaskingView.setVisibility(View.VISIBLE);
                                isPopBottomLayout = true;
                            }
                        });
                return;
            }
            if (listener != null) {
                listener.showKeybordCallback();
            }
            isOpenKeyboarded = true;
        } else {
            if (isOpenKeyboarded) {
                showPublishViewAnim(bottomMaskingView,endHeight, 0,
                        new MyAnimListener() {
                            @Override
                            public void onAnimationEnd() {
                                bottomMaskingView.setVisibility(View.GONE);
                                isPopBottomLayout = false;
                            }
                        });
                if (listener != null) {
                    listener.closeKeybordCallback();
                }
                elseExtraOpe();
                isOpenKeyboarded = false;
            }
        }
    }

    /**
     * 覆盖此方法来做其他操作
     */
    protected void elseExtraOpe() {
    }

//
    /**
     * 显示发布内容弹窗动画
     *
     * @param heiChangeView
     * @param heiStartValue
     * @param heiEndValue
     * @param listener
     */
    protected void showPublishViewAnim(final View heiChangeView,
                                       final float heiStartValue, final float heiEndValue, final MyAnimListener listener) {
        try {
            final ValueAnimator heightAnimator = ValueAnimator.ofFloat(heiStartValue, heiEndValue);
            heightAnimator.setDuration(1);
            heightAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator valueAnimator) {
                    float value = (float) valueAnimator.getAnimatedValue();
                    heiChangeView.setMinimumHeight((int) value);
                    heiChangeView.invalidate();
                }
            });
            heightAnimator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    if (heightAnimator != null) {
                        heightAnimator.cancel();
                        if (listener != null) {
                            listener.onAnimationEnd();
                        }
                    }
                }
            });
            heightAnimator.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void refreshPublishLayout(final View topMaskingView  , final View bottomMaskingView, final LinearLayout emojiContainer ,
                                        Rect rect, float firstHeight , KeybordListener listener) {
        refreshPublishLayout( topMaskingView , bottomMaskingView , emojiContainer ,   rect , firstHeight , 0 , listener );
    }

    /**
     * 刷新发布信息的布局视图
     *
     * @param bottomMaskingView
     * @param rect
     */
    protected void refreshPublishLayout( final View topMaskingView ,
                                         final View bottomMaskingView, final LinearLayout emojiContainer ,
                                         Rect rect,  float firstHeight , int differenceValue  , KeybordListener listener) {
        if (mIsSoftKeyboardShowing) {
            if (!isPopBottomLayout) {
                endHeight = ScreenSizeUtils.getInstance( this ).getScreenHeight() - rect.bottom - differenceValue;
                if( emojiContainer != null ){
                    emojiContainer.setVisibility( View.VISIBLE );
                    endHeight -= emojiContainer.getHeight();
                }
                topViewEndHeight = rect.bottom - firstHeight - Lerist.getStatusBarHeight( this ) - Lerist.dip2px( this , 27);
                bottomMaskingView.setMinimumHeight( rect.bottom );
                //当设备系统版本高于5.0时才显示底部视图，否则会出现输入框被顶到界面最上边
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    bottomMaskingView.setVisibility(View.VISIBLE);
                }
                showPublishViewAnim( topMaskingView , bottomMaskingView,0, endHeight,
                        new MyAnimListener() {
                            @Override
                            public void onAnimationEnd() {
                                if( topMaskingView != null )topMaskingView.setVisibility(View.VISIBLE);
                                bottomMaskingView.setVisibility(View.VISIBLE);
                                isPopBottomLayout = true;
                            }
                        });
                return;
            }
            if (listener != null) {
                listener.showKeybordCallback();
            }
            isOpenKeyboarded = true;
        } else {
            if (isOpenKeyboarded) {
                showPublishViewAnim( topMaskingView , bottomMaskingView,endHeight, 0,
                        new MyAnimListener() {
                            @Override
                            public void onAnimationEnd() {
//                                if( topMaskingView != null )topMaskingView.setVisibility(View.GONE);
                                bottomMaskingView.setVisibility(View.GONE);
                                isPopBottomLayout = false;
                            }
                        });
                if (listener != null) {
                    listener.closeKeybordCallback();
                }
                elseExtraOpe();
                isOpenKeyboarded = false;
            }
        }
    }

    /**
     * 显示发布内容弹窗动画
     *
     * @param heiChangeView
     * @param heiStartValue
     * @param heiEndValue
     * @param listener
     */
    protected void showPublishViewAnim(final View scaleChangeView,final View heiChangeView,
                                       final float heiStartValue, final float heiEndValue, final MyAnimListener listener) {
        try {
            final ValueAnimator heightAnimator = ValueAnimator.ofFloat(heiStartValue, heiEndValue);
            heightAnimator.setDuration(1);
            heightAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator valueAnimator) {
                    float value = (float) valueAnimator.getAnimatedValue();
                    heiChangeView.setMinimumHeight((int) value);
                    heiChangeView.invalidate();
                }
            });
            heightAnimator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    if (heightAnimator != null) {
                        heightAnimator.cancel();
                        if (listener != null) {
                            listener.onAnimationEnd();
                        }
                    }
                }
            });
            heightAnimator.start();
            if (scaleChangeView != null) {
                final ValueAnimator alphaAnimator = ValueAnimator.ofFloat(0, 1);
                alphaAnimator.setDuration(1);
                alphaAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator valueAnimator) {
                        float alpha = (float) alphaAnimator.getAnimatedValue();
                        scaleChangeView.setAlpha(alpha);
                    }
                });
                alphaAnimator.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected interface MyAnimListener {
        void onAnimationEnd();
    }

    public interface KeybordListener {
        void showKeybordCallback();

        void closeKeybordCallback();
    }





    //====================================环信==========================
//    @Override
//    public void onConnected() {
//
//    }
//
//    @Override
//    public void onDisconnected( int  error ) {
//        runOnUiThread(new Runnable() {
//
//            @Override
//            public void run() {
//                if(error == EMError.USER_REMOVED){
//                    // 显示帐号已经被移除
//                }else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
//                    // 显示帐号在其他设备登录
//                    if( !EMClient.getInstance().isConnected() ){
//                        handleLoginAnotherDevice();
//                    }
//                } else {
//                    if (NetUtils.hasNetwork(BaseActivity.this)) {
//                        //连接不到聊天服务器
//                    }else {
//                        //当前网络不可用，请检查网络设置
//                    }
//                }
//            }
//        });
//    }
//
//    protected void handleLoginAnotherDevice(){
//
//        String userId = preferenceUtils.getUserId();
//        String username = "youtangke_"+ userId;
//        String pwd = "youtangke123456";
//        try{
//            //注册失败会抛出HyphenateException
//            EMClient.getInstance().createAccount( username, pwd );//同步方法
//            //注册一个监听连接状态的listener
////            EMClient.getInstance().addConnectionListener(new MyConnectionListener());
//        }catch ( Exception e ){
//            e.printStackTrace();
//        }
//        huanXixIMLogin( "youtangke_"+ userId, pwd  );
//
//
////        final TvOkBtnDialog dialog = new TvOkBtnDialog();
////        dialog.setCancelable( false );
////        dialog.showDialog(getSupportFragmentManager(), resources.getString(R.string.accoun_login_anther_device_hit ),
////                new TvOkBtnDialog.OnDialogListener() {
////                    @Override
////                    public void confirm() {
////                        if( dialog != null ){
////                            dialog.dismiss();
////                        }
////                        preferenceUtils.setLogin( false );
////                        //清除登录信息
////                        preferenceUtils.setLoginInfo( "" );
////                        TagAliasOperatorHelper.getInstance().unbindAlias( BaseActivity.this , preferenceUtils.getUserId() );
////                        //跳转到登录页面
////                        Intent intent = new Intent( BaseActivity.this , LoginActivity.class );
////                        intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
////                        intent.putExtra( "fromClass" , SplashActivity.class.getSimpleName()  );
////                        showActivity( intent );
////                        //退出环信登录状态
////                        EMClient.getInstance().logout(true );
////                        EventBus.getDefault().post( new BaseEvent( BaseEvent.EventCodeContains.FINISH_MAIN_ACTIVITY  ,
////                                BaseEvent.EventNameContains.FINISH_MAIN_ACTIVITY , "" , null ));
////                        EventBus.getDefault().post( new BaseEvent<String>( BaseEvent.EventCodeContains.MAIN_PAGE_CLOSE_PLAY ,
////                                BaseEvent.EventNameContains.MAIN_PAGE_CLOSE_PLAY , "" , null ));
////                    }
////                });
//    }
//    //====================================环信==========================
//
//    public void adaptiveTopRelativeLayout(Context context , View view ){
//        if(MyApplication.getMyApplicationInstance().getPhoneType() == 1 ){
//            RelativeLayout.LayoutParams params =
//                    new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
//            params.setMargins( 0 , CommonUtil.dip2px( context , 24 ) ,0, CommonUtil.dip2px( context , 15 ) );
//            view.setLayoutParams( params );
//        }
//    }
//
//    public void adaptiveTopLinearLayout(Context context , View view ){
//        if(MyApplication.getMyApplicationInstance().getPhoneType() == 1 ){
//            LinearLayout.LayoutParams params =
//                    new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//            params.setMargins( 0 , CommonUtil.dip2px( context , 24 ) ,0, CommonUtil.dip2px( context , 15 ) );
//            view.setLayoutParams( params );
//        }
//    }
//
//    public void adaptiveTitleBar( CustomToolbar customToolbar ){
//        if(MyApplication.getMyApplicationInstance().getPhoneType() == 1 ) {
//            RelativeLayout.LayoutParams params =
//                    new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, CommonUtil.dip2px(this, 88));
//            customToolbar.setPadding(0, CommonUtil.dip2px(this, 24), 0, 0);
//            customToolbar.setLayoutParams(params);
//        }
//    }
//
//
//
//
//
//    /**
//     * 环信IM登录
//     * @param userName
//     * @param password
//     */
//    private void huanXixIMLogin( String userName , String password ){
//        EMClient.getInstance().login(userName,password,new EMCallBack() {//回调
//            @Override
//            public void onSuccess() {
//                EMClient.getInstance().groupManager().loadAllGroups();
//                EMClient.getInstance().chatManager().loadAllConversations();
//                Log.i("TAG", "登录聊天服务器成功！");
//            }
//
//            @Override
//            public void onProgress(int progress, String status) {
//
//            }
//
//            @Override
//            public void onError(int code, String message) {
//                Log.d("main", "登录聊天服务器失败！");
//            }
//        });
//    }

}
